package com.scnu.recruitment.controller.common;


import com.scnu.common.constants.Constant;
import com.scnu.common.exception.BadRequestException;
import com.scnu.common.result.Result;
import com.scnu.oss.AliyunOSSOperator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 通用请求处理
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController
{

    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;



    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public Result uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            long sizeInBytes = file.getSize();
            double sizeInMB = sizeInBytes / (1024.0 * 1024.0);
            if (sizeInMB > Constant.MAX_FILE_SIZE){
                throw new BadRequestException("请勿上传文件大于"+Constant.MAX_FILE_SIZE+"MB的文件！");
            }


            String originalFilename = file.getOriginalFilename();
            String url = aliyunOSSOperator.upload(file.getBytes(),originalFilename);

            return Result.success(url);
        }
        catch (Exception e)
        {
            return Result.error(e.getMessage());
        }
    }

/*    *//**
     * 通用上传请求（多个）
     *//*
    @PostMapping("/uploads")
    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files)
            {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }*/

}
